/**
 * StringToLocalDateConverter.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年1月18日
 */
package com.pshare.util.time;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 字符串转LocalDate转换器
 * 
 */
public class StringToLocalDateConverter implements Converter<String, LocalDate> {

	@Override
	public LocalDate convert(String source) {
		if (StringUtils.isBlank(source)) {
			return null;
		}

		source = source.trim();
		if (!org.springframework.util.StringUtils.hasText(source)) {
			return null;
		}

		int year = 0, month = 0, day = 0;
		int length = source.length();
		if (NumberUtils.isNumber(source)) {
			if (length == 6 || length == 7) {
				year = Integer.parseInt(source.substring(0, 4));
				month = Integer.parseInt(source.substring(4, 5));
				day = Integer.parseInt(source.substring(5));
			} else if (length == 8) {
				year = Integer.parseInt(source.substring(0, 4));
				month = Integer.parseInt(source.substring(4, 6));
				day = Integer.parseInt(source.substring(6));
			}
		} else {
			String[] ss = null;
			if (source.indexOf("-") > 0) {
				ss = source.split("\\-");
			} else if (source.indexOf(".") > 0) {
				ss = source.split("\\.");
			} else {
				throw new IllegalArgumentException("failed to parse LocalDate " + source);
			}
			year = Integer.parseInt(ss[0]);
			month = Integer.parseInt(ss[1]);
			day = Integer.parseInt(ss[2]);
		}

		if (year == 0) {
			throw new IllegalArgumentException("failed to parse LocalDate " + source);
		}

		LocalDate date = LocalDate.of(year, month, day);
		return date;
	}

	public static final DateFormat DF_SHORT = new SimpleDateFormat("yyyyMMdd");
	public static final DateFormat DF_LINE = new SimpleDateFormat("yyyy-MM-dd");
	public static final DateFormat DF_POINT = new SimpleDateFormat("yyyy.MM.dd");

}
